--
-- Author: shunguo.chen
-- Date: 2017-11-27 12:08:05
--
-- MountActivePanel

local IconRender = require("app.widget.renders.IconRender")
local ListViewVertical = require("app.widget.listview.ListViewVertical")

local MountRender = import(".renders.MountRender")
local MountActiveRender = import(".renders.MountActiveRender")
local MountActiveRender2 = import(".renders.MountActiveRender2")
local MOUNT_QUALITY_MAX_STR = L("lua_code_text_349")
local SOUL_NUM_STR = L("lua_code_text_169")

local ClassRef = app.mvc.createPanelClass(...)

function ClassRef.create(node)
    local uiType = 1
    local csdPath = Res.MountActivePanel
    if UD.mountHomeNum > 5 then
        csdPath = Res.MountActivePanel1
        uiType = 2
    end
    local sprite = ClassRef.extend(cc.CSLoader:createNode(csdPath))
    if node == nil then
        ccui.Helper:doLayout(sprite)
    end
    sprite:init({uiType = uiType})
    return sprite
end




function ClassRef:init(data)
    self.super.init(self, data)
    if not data then
        data = {}
    end
    -- bg
    self._starBg = self._ui["Panel/Panel_bg/bg06/2"]
    self._qualityBg = self._ui["Panel/Panel_bg/bg07/2"]
    self._uiType = data.uiType
    if self._uiType == 2 then
        self._activeRendersNum = 10
    else
        self._activeRendersNum = 5
    end
    -- left -- 
    -- active mounts
    local con = self._ui["Panel/Panel_pound"]

    if self._activeRendersNum == 10 then
        self._activeRenders = {0,0,0,0,0,0,0,0,0,0}
        for i=1,5 do
            local node = con:getChildByName("g"..i)
            local render = MountActiveRender.create(node)
            self._activeRenders[i] = render
        end
        
        for i=6,10 do
            local node = con:getChildByName("g"..i)
            local render = MountActiveRender2.create(node)
            self._activeRenders[i] = render
        end
        self:refreshExtendActiveSlot()
    else
        self._activeRenders = {0,0,0,0,0}
        for i=1,5 do
            local node = con:getChildByName("g"..i)
            local render = MountActiveRender.create(node)
            self._activeRenders[i] = render
        end
    end

    con:getChildByName("Button"):addClickEventListener(function()
            executeFunc(self._onOperate, "openAttr", self._mount)
        end)

    -- ScrollView
    local params = {
        renderClass = MountRender,
        perNum = 6,
        gapY = 8,
        paddingLeft = 6,
        paddingRight = 6,
        isMultipleLayer = true,
        cellEventProxy = function(eventName, render)
            if render then
                self:setCurRender(render)
                local data = render:getData()
                if data then
                    local uid = render:getData().uid
                    self:selectActiveRender(uid)
                end
            end
		end,
    }
    self._sv = ListViewVertical.new(self._ui["Panel/ScrollView"], params)
    self._sv:setCellsShareData({listviewType = Enums.MountListViewType.ActivePanelType})
    
    -- right --
    local con = self._ui["Panel/Panel_data"]
    self._nameText = con:findChild("Panel_top/name")
    self._tipsText = con:findChild("Panel_top/tips")

    self._btnTipsText = con:findChild("Panel_bom/Text")
    self._opBtn = con:findChild("Panel_bom/Button")
    self._btnText = self._opBtn:getChildByName("name")

    self._clickBtnUpTime = 0 --防止快速点击
    self._clickBtnDownTime = 0
    self._opBtn:addClickEventListener(function()
            local mount = self._mount
            local nowTime = app.session:getServerTime()
            if self._clickBtnUpTime ~= 0 and nowTime - self._clickBtnUpTime < 1.5 then
                return
            end
            if self._clickBtnDownTime ~= 0 and nowTime - self._clickBtnDownTime < 0.8 then
                return
            end

            self._clickBtnUpTime = nowTime
            if mount:haveMount() then
                executeFunc(self._onOperate, "activeMount", mount)
            else
                executeFunc(self._onOperate, "openGet", mount)
            end
        end)
    self._unequipBtn = con:findChild("Panel_bom/Button_1")
    self._unequipBtn:addClickEventListener(function()
            local nowTime = app.session:getServerTime()
            if self._clickBtnDownTime ~= 0 and nowTime - self._clickBtnDownTime < 1.5 then
                return
            end
            if self._clickBtnUpTime ~= 0 and nowTime - self._clickBtnUpTime < 0.8 then
                return
            end
            self._clickBtnDownTime = nowTime
            executeFunc(self._onOperate, "unactiveMount", self._mount)
        end)

    -- star
    local starPanel = con:getChildByName("Panel_star")
    self._starIcon = starPanel:getChildByName("star")
    self._starText = starPanel:getChildByName("num")

    local tlt = starPanel:findChild("data/data_tlt")
    local num = starPanel:findChild("data/data_num")
    local icon = starPanel:findChild("data_icon/icon")
    num:setVisible(false)
    self._starAttrNodes = {{tlt, num, icon}}

    self._starCostRenders = {0,0,0,0}
    for i=1,4 do
        local node = starPanel:getChildByName("icon0"..i)
        local render = IconRender.create(node)
        render:setTipEnable(true, {x=1/5, y=1/2})
        self._starCostRenders[i] = render
    end

    self._starMaxPanel = starPanel:getChildByName("Panel_max")
    self._starUpBtn = starPanel:getChildByName("Button_up")
    self._starUpBtn:addClickEventListener(function()
        executeFunc(self._onOperate, "openStar", self._mount)
    end)

    -- quality
    local gradePanel = con:getChildByName("Panel_grade")
    self._qualityName = gradePanel:getChildByName("name")
    self._qualityIcon = gradePanel:getChildByName("icon_grade")
    self._qualitySkillIcon = gradePanel:findChild("skill_icon/icon")
    self._qualitySkillName = gradePanel:getChildByName("Text")
    self._qualityMaxPanel = gradePanel:getChildByName("Panel_max")

    self._qualityBarCon = gradePanel:getChildByName("bar")
    self._qualityBarNum = self._qualityBarCon:getChildByName("num")
    self._qualityBar = self._qualityBarCon:getChildByName("LoadingBar")

    self._qualityUpBtn = gradePanel:getChildByName("Button_up")
    self._qualityUpBtn:addClickEventListener(function()
        executeFunc(self._onOperate, "openQuality", self._mount)
    end)

    local clickPanel = gradePanel:getChildByName("Panel_click")
    local boundingBox = clickPanel:getBoundingBox()
    local worldPos = gradePanel:convertToWorldSpace(cc.p(boundingBox.x, boundingBox.y))
    boundingBox.x = worldPos.x
    boundingBox.y = worldPos.y
    clickPanel:addTouchEventListener(function(sender, eventType)
        if not self._mount then return end
        if eventType == ccui.TouchEventType.began then
            UIHandler:hideFloatPanel()
            local mount = self._mount
            local params = {
                tipsType = Enums.TipsType.classSkill,
                dataTemp = mount:getSkill(),
                boundingBox = boundingBox
            }
            app:dispatchCustomEvent("EVENT_OPEN_FLOAT", {params=params})
        elseif eventType == ccui.TouchEventType.canceled or eventType == ccui.TouchEventType.ended then
            UIHandler:hideFloatPanel()
        end
    end)

    self:registerViewEvent({
        {name = ViewEvent.Mount_OpenExtendSlot, callback = handler(self, self._onOpenExtendActiveSlot)},
    })
end

function ClassRef:_onOpenExtendActiveSlot()
    self:refreshExtendActiveSlot()
end

function ClassRef:refreshExtendActiveSlot()
    if self._uiType == 2 then
        for i = 6, UD.mountHomeNum do
            local activeRender = self._activeRenders[i]
            if activeRender then
                activeRender:setLock(false)
            end
        end
    end
end

-- 122，点击兽栏置入按钮
-- 123，坐骑被动提示
-- 130，坐骑升星按钮
function ClassRef:getGuideNode(id)
    if id == 122 then
        return self._opBtn
    elseif id == 123 then
        return self._activeRenders[1]
    elseif id == 130 then
        return self._starUpBtn
    end
end

function ClassRef:onOperate(cb)
    self._onOperate = cb
end

function ClassRef:getScrollView()
    return self._sv
end

function ClassRef:getActiveRenders()
    return self._activeRenders
end

function ClassRef:setCurActiveRender(render)
    if self._curActiveRender and self._curActiveRender ~= render then
        self._curActiveRender:setSelected(false)
    end
    self._curActiveRender = render
end

function ClassRef:setRenderSelected(uid, b)
    self._sv:foreachCellModels(function(cellModel, data)
        if data.uid == uid then
            if cellModel.cell then
                cellModel.cell:setSelected(b)
            else
                cellModel:setSelected(b)
            end
            if b then
                self._curSelectRenderData = data
            end
            return true
        end
    end)
end

function ClassRef:selectRender(uid, isRefresh)
    isRefresh = isRefresh or false
    if self._curSelectRenderData and self._curSelectRenderData.uid ~= uid then
        self:setRenderSelected(self._curSelectRenderData.uid, false)
    end
    self:setRenderSelected(uid, true)
    if isRefresh then
        self:setCurRenderData(self._curSelectRenderData)
    end
end

function ClassRef:selectActiveRender(uid)
    local findRender
    for i,render in ipairs(self._activeRenders) do
        local data = render:getData()
        if data then
            
            if data.uid == uid then
                render:setSelected(true)
                findRender = render
                break
            end
        end
    end
    self:setCurActiveRender(findRender)
end

function ClassRef:setCurRender(render)
    local data = render:getData()
    self:setCurRenderData(data)
end

function ClassRef:setCurRenderData(renderData)
    if not renderData then
        return
    end
    if self._curSelectRenderData then
        if self._curSelectRenderData.uid ~= renderData.uid then
            self:setRenderSelected(self._curSelectRenderData.uid, false)
            self:setRenderSelected(renderData.uid, true)
        end
    else
        self:setRenderSelected(renderData.uid, true)
    end
    self:refreshMount(renderData)
end

function ClassRef:clearSelect()
    if self._curSelectRenderData then
        self:setRenderSelected(self._curSelectRenderData.uid, false)
        self._curSelectRenderData = nil
    end
    if self._curActiveRender then
        self._curActiveRender:setSelected(false)
        self._curActiveRender = nil
    end
end

function ClassRef:getMount()
    return self._mount
end

function ClassRef:refreshMount(mount)
    mount = mount or self._mount
    self._mount = mount
    
    local quality = mount:getQuality()
    self._nameText:setString(mount:getName())
    self._nameText:setColor(Enums.QualityColor[quality])
    self._tipsText:setString(mount:getState())

    local hasMount = mount:haveMount()
    local canUnequip = false
    if hasMount then
        if mount:isActive() then
            canUnequip = true
            self._btnTipsText:setString(L("takeouteffect"))
        else
            self._btnText:setString(L("equipmount"))
            self._btnTipsText:setString(L("activationeffect"))
        end
    else
        self._btnText:setString(L("text_11800008"))
        self._btnTipsText:setString(L("uhavenotthismount"))
    end

    self._opBtn:setVisible(not canUnequip)
    self._unequipBtn:setVisible(canUnequip)

    self._starBg:setVisible(hasMount)
    self._qualityBg:setVisible(hasMount)

    self:refreshStar()
    self:refreshQuality()
end

function ClassRef:refreshStar()
    local mount = self._mount

    -- starIcon
    local star = mount:getStar()
    self._starText:setString(star)
    self._starIcon:loadTexture(string.format(Res.MountStarPath, star))

    -- attrNodes
    local attrs = mount:getStarAttrs()
    for i,v in ipairs(self._starAttrNodes) do
        local attr = attrs[i]
        local name, value, icon = GD:getPropShowData(attr[1], attr[2])
        v[1]:setString(string.format("%s +%d",name,value))
        --v[2]:setString("+"..value)
        v[3]:loadTexture(icon)

    end

    -- costItems upBtn
    local haveMount = mount:haveMount()
    local isMaxStar = mount:isMaxStar()
    local canUp = haveMount and not isMaxStar

    self._starMaxPanel:setVisible(haveMount and isMaxStar)
    self._starUpBtn:setVisible(canUp)
    for i,v in ipairs(self._starCostRenders) do
        v:setVisible(canUp)
    end
    if canUp then
        self:refreshStarCollect()
    end
end

function ClassRef:refreshStarCollect()
    local items = self._mount:getStarCostItems()
    for i,v in ipairs(self._starCostRenders) do
        v:setData(items[i])
        local hasNum = UD:getItemAmountByTid(items[i].tid)
        v:setHasAmount(hasNum)
    end
end

function ClassRef:refreshQuality()
    local mount = self._mount
    local quality = mount:getQuality()

    -- name icon
    self._qualityName:setString(L(Enums.QualityName[quality]))
    self._qualityName:setColor(Enums.QualityColor[quality])
    self._qualityIcon:loadTexture(string.format(Res.MountQualityPath, quality))

    -- skill
    local skill = mount:getSkill()
    self._qualitySkillIcon:loadTexture(skill:getIcon())
    self._qualitySkillName:setString(skill:getName())

    -- costItem upBtn
    local canUp = true
    local tipStr
    if mount:haveMount() then
        if mount:isMaxQuality() then
            canUp = false
            tipStr = MOUNT_QUALITY_MAX_STR
        end
    else
        canUp = false
        tipStr = ""
    end

    local haveMount = mount:haveMount()
    local isMaxQuality = mount:isMaxQuality()
    local canUp = haveMount and not isMaxQuality

    self._qualityMaxPanel:setVisible(haveMount and isMaxQuality)
    self._qualityUpBtn:setVisible(canUp)
    self._qualityBarCon:setVisible(canUp)
    if canUp then
        self:refreshMountCollect()
    end
end

function ClassRef:refreshMountCollect()
    local haveNum, needNum = self._mount:getQualityCostNum()
    local per = math.min(haveNum/needNum*100, 100)
    self._qualityBarNum:setString(string.format(SOUL_NUM_STR, haveNum, needNum))
    self._qualityBar:setPercent(per)
end


function ClassRef:reloadData(data, notReset)
    if not notReset then
        self._sv:reloadData(data) 
    else
        self._sv:reloadData(data, {startIndex = 1})
    end
end

function ClassRef:refreshScrollView()
    self._sv:refreshVisibleCells()
end

function ClassRef:setSelectedByIndex(index)
    local data = self._sv:getDataByIndex(index)
    if data then
        self:setCurRenderData(data)
    end
end


function ClassRef:refreshActiveRenders()
    for k, v in ipairs(self._activeRenders) do
        v:refresh()
    end
end

-- 刷新所有元素红点
function ClassRef:refreshRedPoint()
    self._sv:foreachVisibleCells(function(cell)
        cell:updateRedPoint()
    end)
end

return ClassRef